package com.alpha.eceasy.mall.api.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * mybatis映射字符串数组处理
 *
 * @author huangpengfei
 * @since 2024-03-22
 */
public class ListStringHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, String.join(",", parameter));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return List.of(Optional.ofNullable(rs.getString(columnName)).map(s -> s.split(",")).orElse(new String[]{""}));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return List.of(Optional.ofNullable(rs.getString(columnIndex)).map(s -> s.split(",")).orElse(new String[]{""}));
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return List.of(Optional.ofNullable(cs.getString(columnIndex)).map(s -> s.split(",")).orElse(new String[]{""}));
    }
}
